package net.lesscoding;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import net.lesscoding.common.Config;
import net.lesscoding.message.LoginRequestMessage;
import net.lesscoding.message.Message;
import net.lesscoding.protocol.Serializer;
import net.lesscoding.protocol.SharedMessageCodec;
import org.junit.Test;

/**
 * @author eleven
 * @date 2024/12/3 11:14
 * @apiNote
 */
@Slf4j
public class SerializerTest {
    @Test
    public void serializerTest() {
        LoggingHandler debugLogger = new LoggingHandler(LogLevel.DEBUG);
        SharedMessageCodec messageCodec = new SharedMessageCodec();
        EmbeddedChannel channel = new EmbeddedChannel(debugLogger, messageCodec, debugLogger);
        LoginRequestMessage loginRequestMessage = new LoginRequestMessage("zhangsan", "123");
        //channel.writeOutbound(loginRequestMessage);
        channel.writeInbound(messageToBytes(loginRequestMessage));
    }

    public static ByteBuf messageToBytes(Message msg) {
        int ordinal = Config.getSerializerAlgorithm().ordinal();
        ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer();
        buffer.writeBytes("AreYouOk".getBytes())
                .writeByte(1)
                .writeByte(ordinal)
                .writeByte(msg.getMessageType())
                .writeInt(msg.getSequenceId())
                .writeByte(0xff);
        byte[] bytes = Serializer.Algorithm.values()[ordinal].serialize(msg);
        buffer.writeInt(bytes.length);
        buffer.writeBytes(bytes);
        return buffer;
    }
}
